/* eslint-disable operator-assignment */

const getQuestion = (map, no) => {
  const q = map[no];

  if (q) {
    const { objectAnswer, answerOptions, questionInfo } = q;
    const index = answerOptions.findIndex((e) => e.option === objectAnswer * 1);

    let result = {};

    if (questionInfo && questionInfo.trim().length > 0) {
      result = {
        name: questionInfo,
      };
    } else {
      result = {
        name: q.questionContent,
      };
    }

    if (index !== -1) {
      const children = answerOptions.map((i) => {
        const { optionContent } = i;
        return {
          name: optionContent,
        };
      });

      result = { ...result, score: answerOptions[index].optionScore, children };
    }

    return result;
  }

  console.log('lose question:', no);

  return {
    name: `X-${no}`,
    score: '',
  };
};

const getMap = (answer) => {
  const map = {};
  answer.answerQuestions.forEach((i) => {
    map[i.questionNo] = i;
  });
  return map;
};

const sortingDefine = {
  'S0075:感官知觉领域': ['视觉应用', '听觉应用', '触觉应用', '味嗅觉刺激', '前庭及本体觉刺激'],
  'S0075:粗大动作领域': ['姿势控制', '转换姿势', '移动能力', '简单运动技能'],
  'S0075:细动作领域': ['抓放能力', '操作能力', '简单劳作及书写技能'],
  'S0075:生活自理领域': ['饮食', '如厕', '清洁卫生', '穿著'],
  'S0075:语言沟通领域': ['言语机转', '语言理解', '口语表达', '沟通能力'],
  'S0075:认知领域': [
    '概念理解',
    '物体恒存概念',
    '简单因果概念',
    '基本物概念',
    '颜色概念',
    '形状概念',
    '比较概念',
    '空间概念',
    '符号概念',
    '数概念',
    '顺序概念',
    '模仿',
    '记忆',
    '配对分类',
    '逻辑思考',
    '解决问题',
    '简单阅读',
  ],
  'S0075:社会适应领域': ['自我概念', '环境适应', '人际互动', '游戏特质'],
};

const listToMap = (ary) => {
  const v = {};
  ary.forEach((item, index) => {
    v[item] = ary.length - index;
  });

  return v;
};

const sorting = (code, scaleName, scoringResults) => {
  const define = sortingDefine[`${code}:${scaleName}`];

  if (define) {
    const map = listToMap(define);
    const sorted = scoringResults.sort((a, b) => {
      return map[b.scoreName] - map[a.scoreName];
    });

    return sorted;
  }

  return [...scoringResults];
};

export function getData (code, reports, answers) {
  const data = [];
  reports.forEach((report, i) => {
    const { scaleName, scoringResults } = report;
    const map = getMap(answers[i]);
    const item = {
      name: scaleName,
      children: [],
    };

    const parents = {};
    sorting(code, scaleName, scoringResults).forEach((result) => {
      const { scope, score, scoreName, questions } = result;

      const sortQS = questions.sort((a, b) => {
        return a - b;
      });

      if (scope === 'TOTAL_SCORE') {
        item.score = score * 1; // 維度總分後台已經計算.不用再累加
      } else if (scope === 'DIMENSIONS') {
        const child = {
          name: scoreName,
          scope,
          score,
          children: sortQS.map((no) => {
            return getQuestion(map, no);
          }),
        };

        item.children.push(child);
      } else {
        const child = {
          name: scoreName,
          scope,
          score,
          children: questions.map((no) => {
            return getQuestion(map, no);
          }),
        };

        if (!parents[scope]) {
          parents[scope] = { score: 0, children: [] };
        }

        parents[scope].score = parents[scope].score + child.score * 1;
        parents[scope].children.push(child);
      }
    });

    Object.keys(parents).forEach((key) => {
      const v = parents[key];
      // 固定在第一位
      item.children.unshift({
        name: key,
        score: v.score,
        children: v.children,
      });
    });

    data.push(item);
  });

  return data;
};
